package com.revenant.driver.ui.activity;

import android.app.AppOpsManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.Manifest;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.AppOpsManagerCompat;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.AMapLocationQualityReport;
import com.amap.api.navi.CheckPermissionsActivity;
import com.apkfuns.logutils.LogUtils;
import com.bumptech.glide.Glide;
import com.hdgq.locationlib.LocationOpenApi;
import com.hdgq.locationlib.entity.ShippingNoteInfo;
import com.hdgq.locationlib.listener.OnResultListener;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.camera.CheckPermission;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.nanchen.compresshelper.CompressHelper;
import com.revenant.driver.BuildConfig;
import com.revenant.driver.R;
import com.revenant.driver.adapter.Driver.OrderDetailBean;
import com.revenant.driver.base.BaseActivity;
import com.revenant.driver.bean.BaseBean.BaseTestBean;
import com.revenant.driver.bean.BaseBean.MessageEvent;
import com.revenant.driver.bean.DriverTrackBean;
import com.revenant.driver.bean.ShipperBean.ChaKanBangDan;
import com.revenant.driver.bean.ShipperBean.FileUploadBean;
import com.revenant.driver.utils.Constants;
import com.revenant.driver.utils.DlgUtils;
import com.revenant.driver.utils.EventBusUtil;
import com.revenant.driver.utils.GsonUtil;
import com.revenant.driver.utils.LocatinNoDataService;
import com.revenant.driver.utils.LocationService;
import com.revenant.driver.utils.PermissionConstants;
import com.revenant.driver.utils.PermissionHelper;
import com.revenant.driver.utils.PermissionUtils;
import com.revenant.driver.utils.SPUtils;
import com.revenant.driver.utils.Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.revenant.driver.bean.BaseBean.MyEventCode.Location_Error_SIGAL;
import static com.revenant.driver.bean.BaseBean.MyEventCode.Location_Success_SIGAL;
import static com.revenant.driver.bean.BaseBean.MyEventCode.Order_Type_SIGAL;
import static com.revenant.driver.utils.Constants.Driver_GetDriverCar_info;
import static com.revenant.driver.utils.Constants.Driver_JustOrder_Order_Detail;
import static com.revenant.driver.utils.Constants.Driver_Location_Upload;
import static com.revenant.driver.utils.Constants.UpdateDriverJtbInfoNew;
import static com.revenant.driver.utils.Constants.UpdateJtbStatus;
import static com.revenant.driver.utils.Constants.Update_Zhong_Jiao;
import static com.revenant.driver.utils.Constants.UploadFile;
import static com.revenant.driver.utils.Constants.Upload_BangDan_New;

public class DriverShangChuanBangDanActivity extends BaseActivity {
    @BindView(R.id.input)
    EditText input;
    @BindView(R.id.show_title)
    LinearLayout showTitle;
    @BindView(R.id.uploadimage)
    ImageView uploadimage;
    @BindView(R.id.upload)
    Button upload;
    @BindView(R.id.amount)
    TextView amount;
    @BindView(R.id.shipperamount)
    TextView shipperamount;
    private Context context;
    private int type = 0;
    private int goodsid = 0;
    private String goodno = "";
    private List<String> mList = Arrays.asList("上传装货磅单", "上传卸货磅单");
    private String uploadurl = "";
    private List<LocalMedia> selectList = new ArrayList<>();
    private ShippingNoteInfo[] shippingNoteInfos;
    private String endCountrySubdivisionCode;
    private String orderdescode;
    private String orderloadcode;
    private double orderamount;
    private int typee = 1;
    private double aa = 0.0;
    private double bb = 0.0;
    private double ss = 0.0;
    private double dd = 0.0;
    private double kk = 0.0;
    private double amountt = 0.0;
    private AMapLocation location;

    private int locationsuccess=0;



    public static final String TAG = "LocationService";
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    private static volatile AMapLocation lastLocation;

    private boolean locationAmi =false;


    @Override
    public int getContentViewResId() {
        return R.layout.activity_driver_shangchuanbangdan;
    }

    @Override
    public void initView() {
        context = this;

        boolean locationEnabled = isLocationEnabled();

//        initLocation();
//        startLocation();

//        checkLocationPermission();

        if (locationEnabled) {
        } else {
            Toast.makeText(context, "请开启位置服务", Toast.LENGTH_SHORT).show();
        }

        checkPermission(context);

        Bundle bundle = getIntent().getExtras();
        type = bundle.getInt("uploadtype");
        goodsid = bundle.getInt("uploadid");
        LookBangdan(goodsid);
//        getGoodsDetail(goodsid);
        goodno = bundle.getString("orderno");
        orderdescode = bundle.getString("orderdescode");
        orderloadcode = bundle.getString("orderloadcode");
//        orderamount = Double.valueOf(bundle.getString("orderamount"));
        setcenterTitle(mList.get(type));

        input.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!input.getText().toString().trim().isEmpty()) {
                    Double aweight = Double.valueOf(Double.valueOf(input.getText().toString()) * orderamount);
                    String resultweight = String.format("%.2f", aweight);
                    amount.setText(String.valueOf(resultweight));
                } else {
                    input.setHint("请输入数值");
                    amount.setText("0");
                }
            }
        });

    }

    @Override
    public void leftbarclick() {
        super.leftbarclick();
        finish();
    }

    @Override
    public void initData() {

    }


    public void checkLocationPermission() {
        if (!PermissionHelper.isLocServiceEnable(this)) {//检测是否开启定位服务
            DlgUtils.showLocServiceDialog(this);
        } else {//检测用户是否将当前应用的定位权限拒绝
            int checkResult = PermissionHelper.checkOp(this, 2, AppOpsManager.OPSTR_FINE_LOCATION);//其中2代表AppOpsManager.OP_GPS，如果要判断悬浮框权限，第二个参数需换成24即AppOpsManager。OP_SYSTEM_ALERT_WINDOW及，第三个参数需要换成AppOpsManager.OPSTR_SYSTEM_ALERT_WINDOW
            int checkResult2 = PermissionHelper.checkOp(this, 1, AppOpsManager.OPSTR_FINE_LOCATION);
            if (AppOpsManagerCompat.MODE_IGNORED == checkResult || AppOpsManagerCompat.MODE_IGNORED == checkResult2) {
                DlgUtils.showLocIgnoredDialog(this);
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.uploadimage, R.id.upload})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.uploadimage:
                selectimage();
                break;
            case R.id.upload:
                if (input.getText().toString().trim().isEmpty()) {
                    showToast("数值不能为空");
                } else if (decimalcount(input, "重量填写完备")) {
                } else if (uploadurl.isEmpty()) {
                    showToast("上传磅单不能为空");
                }else if (!isLocationEnabled()){
                    Toast.makeText(context, "请开启位置服务", Toast.LENGTH_SHORT).show();
                }else {
                    showDig();
                    if (LocationService.getLastLocation() == null) {
                        if (LocatinNoDataService.getLastLocation() != null) {
                            location = LocatinNoDataService.getLastLocation();
                        } else {

                        }
                    } else {
                        location = LocationService.getLastLocation();
                    }
                    if (location != null) {

                        String traceDesc = "";
                        ShippingNoteInfo shippingNoteInfo = new ShippingNoteInfo();
                        shippingNoteInfo.setShippingNoteNumber(goodno);
                        shippingNoteInfo.setSerialNumber("0000");
                        shippingNoteInfos = new ShippingNoteInfo[1];

                        if (type == 0) {

                            // TODO: 2020/4/29
//                        /*版本是*/
                            if (location != null) {
                                if (location.getAdCode().isEmpty()) {
                                    shippingNoteInfo.setStartCountrySubdivisionCode(orderloadcode);

                                } else {
                                    shippingNoteInfo.setStartCountrySubdivisionCode(location.getAdCode());
                                }
                                shippingNoteInfo.setEndCountrySubdivisionCode(orderdescode);
//                                traceDesc = location.getAddress();
//                                uploadTrack(String.valueOf(location.tLatitude()), String.valueOf(location.getLatitude()), traceDesc, "1");
                                shippingNoteInfos[0] = shippingNoteInfo;
                                UpLoadBangdan(
                                        String.valueOf(goodsid),
                                        input.getText().toString().trim(),
                                        uploadurl,
                                        String.valueOf(location.getLatitude()),
                                        String.valueOf(location.getLongitude()),
                                        location.getAddress(),
                                        location.getAdCode()


                                );

                                startLoation();


                            }


                        } else if (type == 1) {
                            // TODO: 2020/4/29
//                        /*版本是*/
                            if (location != null) {
                                shippingNoteInfo.setStartCountrySubdivisionCode(orderloadcode);
                                if (location.getAdCode().isEmpty()) {
                                    shippingNoteInfo.setEndCountrySubdivisionCode(orderdescode);
                                } else {
                                    shippingNoteInfo.setEndCountrySubdivisionCode(location.getAdCode());
                                }
                                traceDesc = location.getAddress();
//                                uploadTrack(String.valueOf(location.getLatitude()), String.valueOf(location.getLatitude()), traceDesc, "3");
                                shippingNoteInfos[0] = shippingNoteInfo;

                                UpLoadBangdanXieHuo(
                                        String.valueOf(goodsid),
                                        input.getText().toString().trim(),
                                        uploadurl,
                                        String.valueOf(location.getLatitude()),
                                        String.valueOf(location.getLongitude()),
                                        location.getAddress(),
                                        location.getAdCode()
                                );
                                stopLoation();

                            }
                        }
                    } else {
                        if (LocationService.getLastLocation() == null) {
                            if (LocatinNoDataService.getLastLocation() == null) {
                                Intent serviceIntend = new Intent(this, LocatinNoDataService.class);
                                startService(serviceIntend);

                            }else {
                                location = LocatinNoDataService.getLastLocation();
                            }
                        } else {
                            location = LocationService.getLastLocation();
                        }
                        boolean locationEnabled = isLocationEnabled();
                        if (locationEnabled) {
                        } else {
                            Toast.makeText(context, "请开启位置服务", Toast.LENGTH_SHORT).show();
                        }

                        dismissDig();
                        if (locationsuccess==1){
                            showMissingPermissionDialog("定位");
                        }else {
                            showToast("请稍后再试");
                        }


                    }

                }

                break;
        }
    }

    private void startLoation() {
        LocationOpenApi.start(context,
                shippingNoteInfos, new OnResultListener() {
                    @Override
                    public void onSuccess() {
//                        uploadBangdanone(goodsid, input.getText().toString().trim(), uploadurl,"1");
                        jiaotongbustart(goodsid, 1);
                    }

                    @Override
                    public void onFailure(String s, String s1) {
                        jiaotongbustart(goodsid, 0);
//                        uploadBangdanone(goodsid, input.getText().toString().trim(), uploadurl,"0");
                    }
                });
    }

    private void UpLoadBangdan(
            String orderId,
            String firstbillContent,
            String firstbillPhoto,
            String startX,
            String startY,
            String startDetailAddress,
            String startAreaCode
    ) {
        OkGo.<String>post(UpdateDriverJtbInfoNew)
                .params("orderId", orderId)
                .params("firstbillContent", firstbillContent)
                .params("firstbillPhoto", firstbillPhoto)
                .params("amount", String.valueOf(Double.valueOf(firstbillContent) * orderamount))
                .params("startX", startX)
                .params("startY", startY)
                .params("startDetailAddress", startDetailAddress)
                .params("startAreaCode", startAreaCode)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        dismissDig();

                        MessageEvent event = new MessageEvent(Order_Type_SIGAL);
                        EventBusUtil.sendEvent(event);
                        finish();

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDig();

                    }
                });
    }

    private void UpLoadBangdanXieHuo(
            String orderId,
            String secondbillContent,
            String secondbillPhoto,
            String endX,
            String endY,
            String endDetailAddress,
            String endAreaCode
    ) {
        OkGo.<String>post(UpdateDriverJtbInfoNew)
                .params("orderId", orderId)
                .params("secondbillContent", secondbillContent)
                .params("secondbillPhoto", secondbillPhoto)
                .params("amount", caul(typee, aa, Double.valueOf(secondbillContent), ss, dd, kk, amountt))
                .params("endX", endX)
                .params("endY", endY)
                .params("endDetailAddress", endDetailAddress)
                .params("endAreaCode", endAreaCode)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        dismissDig();
                        MessageEvent event = new MessageEvent(Order_Type_SIGAL);
                        EventBusUtil.sendEvent(event);
                        finish();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDig();

                    }
                });
    }

    private void stopLoation() {
        LocationOpenApi.stop(context,
                shippingNoteInfos, new OnResultListener() {
                    @Override
                    public void onSuccess() {
//                        uploadBangdantwo(goodsid, String.valueOf(location.getLongitude()), String.valueOf(location.getLatitude()), input.getText().toString().trim(), uploadurl,"1");

                        jiaotongbuend(goodsid, 1);
                    }

                    @Override
                    public void onFailure(String s, String s1) {
                        jiaotongbuend(goodsid, 0);
//                        uploadBangdantwo(goodsid, String.valueOf(location.getLongitude()), String.valueOf(location.getLatitude()), input.getText().toString().trim(), uploadurl,"0");

                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    for (LocalMedia media : selectList) {
                        if (!selectList.isEmpty()) {
//                            Glide.with(this).load(media.getPath()).centerCrop().
//                                    into(uploadImage);
//                            uploadAvatar(media.getPath());
                            String url = media.getPath().startsWith("content://") ? media.getAndroidQToPath() : media.getPath();
                            uploadAvatar(url);
                        }
                        break;
                    }
            }
        }
    }

    private void uploadAvatar(final String path) {
        showDig();
        File file = new File(path);
        File newfile = CompressHelper.getDefault(context).compressToFile(file);

        OkGo.<String>post(UploadFile)
                .tag(this)
                .isMultipart(true)

                .params("file", newfile)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.code() == 200) {
                            FileUploadBean fileUploadBean = GsonUtil.parseJsonWithGson(response.body(), FileUploadBean.class);
                            if (fileUploadBean.getCode().equals("0")) {
                                uploadurl = fileUploadBean.getData().getUrl();
                                Glide.with(context).load(fileUploadBean.getData().getUrl()).centerCrop().
                                        into(uploadimage);
                                dismissDig();

                            } else {
                                showToast(fileUploadBean.getMsg());
                                dismissDig();
                            }
                        } else {
                            dismissDig();
                            showToast(response.message());
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        LogUtils.d("失败是" + response.message());
                        dismissDig();
                    }
                });
    }

    private void selectimage() {

        showBottomSheetDialog(DriverShangChuanBangDanActivity.this);
//        PictureSelector.create(this)
//                .openGallery(PictureMimeType.ofImage())
//                .maxSelectNum(1)
//                .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
//                .forResult(PictureConfig.CHOOSE_REQUEST);

    }

    private void uploadBangdanone(
            int orderId,
            String firstbillContent,
            String firstbillPhoto,
            String type

    ) {
        OkGo.<String>post(Upload_BangDan_New)
                .params("orderId", orderId)
                .params("firstbillContent", firstbillContent)
                .params("firstbillPhoto", firstbillPhoto)
                .params("amount", String.valueOf(Double.valueOf(firstbillContent) * orderamount))
                .params("isUploadStart", type)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        dismissDig();
                        FileUploadBean fileUploadBean = GsonUtil.parseJsonWithGson(response.body(), FileUploadBean.class);
                        if (fileUploadBean.getCode().equals("0")) {
                            MessageEvent event = new MessageEvent(Order_Type_SIGAL);
                            EventBusUtil.sendEvent(event);
                            showToast(fileUploadBean.getMsg());
                            initDataRecyclerview(
                                    SPUtils.getLongitude(context),
                                    SPUtils.getLatitude(context)
                            );
                            finish();
                        } else {
                            showToast(fileUploadBean.getMsg());
                        }

                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDig();

                    }
                });
    }


    private void uploadBangdantwo(
            int orderId,
            String x,
            String y,
            String secondbillContent,
            String secondbillPhoto,
            String type

    ) {
        OkGo.<String>post(Upload_BangDan_New)
                .params("orderId", orderId)
                .params("x", x)
                .params("y", y)
                .params("secondbillContent", secondbillContent)
                .params("secondbillPhoto", secondbillPhoto)
                .params("amount", caul(typee, aa, Double.valueOf(secondbillContent), ss, dd, kk, amountt))
                .params("isUploadEnd", type)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        dismissDig();
                        FileUploadBean fileUploadBean = GsonUtil.parseJsonWithGson(response.body(), FileUploadBean.class);
                        if (fileUploadBean.getCode().equals("0")) {
                            MessageEvent event = new MessageEvent(Order_Type_SIGAL);
                            EventBusUtil.sendEvent(event);
                            showToast(fileUploadBean.getMsg());
                            initDataRecyclerview(
                                    SPUtils.getLongitude(context),
                                    SPUtils.getLatitude(context)
                            );
//                            stopLoation();
                            finish();
                        } else {
                            showToast(fileUploadBean.getMsg());
                        }


                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDig();
                    }
                });
    }


    private void initDataRecyclerview(String lon, String lan) {
        OkGo.<String>post(Driver_GetDriverCar_info)
                .params("userId", SPUtils.getAccounId(context))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        dismissDig();
                        DriverTrackBean listBean = GsonUtil.parseJsonWithGson(response.body(), DriverTrackBean.class);
                        if (listBean.getCode().equals("0")) {
                            if (Integer.valueOf((Integer) listBean.getData()) == 0) {
                                querensiconfirm(lon, lan);

                            }
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDig();
                    }
                });
    }

    private void querensiconfirm(String lon, String lan) {
        OkGo.<String>post(Driver_Location_Upload)
                .params("x", lan)
                .params("y", lon)
                .params("userId", SPUtils.getAccounId(context))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        dismissDig();
                        DriverTrackBean queRenSiBean = GsonUtil.parseJsonWithGson(response.body(), DriverTrackBean.class);
                        if (queRenSiBean.getCode().equals("0")) {
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDig();
                    }
                });
    }

    private boolean decimalcount(TextView textView, String msg) {
        if (textView.getText().toString().endsWith(".")) {
            showToast(msg);
            return true;
        }
        return false;
    }

    /*上传司机轨迹（中交）*/

    private void uploadTrack(String lon, String lan, String traceDesc, String status) {
        OkGo.<String>post(Update_Zhong_Jiao)
                .params("x", lan)
                .params("y", lon)
                .params("userId", SPUtils.getAccounId(context))
                .params("traceDesc", traceDesc)
                .params("status", status)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                        com.blankj.utilcode.util.LogUtils.d("test", response.body());
                        BaseTestBean testBean = GsonUtil.parseJsonWithGson(response.body(), BaseTestBean.class);
                        if (testBean.getCode().contains("0")) {


                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });
    }


    private void getGoodsDetail(int dataid) {
        OkGo.<String>get(Driver_JustOrder_Order_Detail)
                .params("id", dataid)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        OrderDetailBean detailBean = GsonUtil.parseJsonWithGson(response.body(), OrderDetailBean.class);
                        if (detailBean.getCode().equals("0")) {

                        }


                    }
                });
    }

    private void LookBangdan(int bangdanid) {
        showDig();
        OkGo.<String>get(Constants.Look_BangDan)
                .params("orderId", bangdanid)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        dismissDig();
                        ChaKanBangDan chaKanBangDan = GsonUtil.parseJsonWithGson(response.body(), ChaKanBangDan.class);
                        if (chaKanBangDan.getCode().contains("0")) {
                            orderamount = Double.valueOf(chaKanBangDan.getData().getPrice());
                            if (chaKanBangDan.getData().getRoadConsumption() != null) {
                                if (chaKanBangDan.getData().getFirstbillContent() != null) {

                                    typee = chaKanBangDan.getData().getDanWei();
                                    aa = Double.valueOf(chaKanBangDan.getData().getFirstbillContent());
                                    ss = Double.valueOf(chaKanBangDan.getData().getPrice());
                                    dd = Double.valueOf(chaKanBangDan.getData().getRoadConsumption());
                                    kk = 0.0;
                                    amountt = Double.valueOf(chaKanBangDan.getData().getAmount());
                                }
                                if (chaKanBangDan.getData().getRoadConsumption() != null) {
                                    shipperamount.setText(chaKanBangDan.getData().getRoadConsumption());
                                }


                            }
                        } else {
                            showToast(chaKanBangDan.getMsg());
                        }


                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDig();
                    }
                });
    }

    private String caul(int type, double a, double b, double s, double d, double k, double amount) {
        String result = "";
        if (type == 1) {
            if (a > b) {
                if ((b + d) >= a) {
                    result = String.valueOf(a * s - k);

                } else {
                    result = String.valueOf(b * s - k);
                }

            } else {
                result = String.valueOf(a * s - k);

            }

        } else {
            result = String.valueOf(amount - k);

        }
        Double aweight = Double.valueOf(result);
        String resultweight = String.format("%.2f", aweight);
        return resultweight;
    }

    private void jiaotongbustart(int orderId, int isUploadStart) {
        OkGo.<String>post(UpdateJtbStatus)
                .params("orderId", orderId)
                .params("type", 1)
                .params("isUploadStart", isUploadStart)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        dismissDig();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDig();
                    }
                });
    }


    private void jiaotongbuend(int orderId, int isUploadEnd) {
        OkGo.<String>post(UpdateJtbStatus)
                .params("orderId", orderId)
                .params("type", 2)
                .params("isUploadEnd", isUploadEnd)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                    }
                });
    }



    public void checkPermission(Context context) {



        PermissionUtils.permission(
                PermissionConstants.STORAGE,
                PermissionConstants.LOCATION,
                PermissionConstants.CAMERA)
                .rationale(new PermissionUtils.OnRationaleListener() {
                    @Override
                    public void rationale(ShouldRequest shouldRequest) {
                        shouldRequest.again(true);
                    }
                })
                .callback(new PermissionUtils.FullCallback() {
                    @Override
                    public void onGranted(List<String> permissionsGranted) {

                        if (LocationService.getLastLocation() == null) {
                            if (LocatinNoDataService.getLastLocation() == null) {
                                if (location == null) {
                                    Intent serviceIntend = new Intent(context, LocatinNoDataService.class);
                                    startService(serviceIntend);

                                }

                            } else {
                                location = LocatinNoDataService.getLastLocation();
                            }
                        } else {
                            location = LocationService.getLastLocation();
                        }

                    }

                    @Override
                    public void onDenied(List<String> permissionsDeniedForever, List<String> permissionsDenied) {
                        if (!permissionsDeniedForever.isEmpty()) {
                            showMissingPermissionDialog("必须");
                            return;
                        }
                        checkPermission(context);
                    }
                })
                .request();


    }

    public void showMissingPermissionDialog(String s) {
        AlertDialog.Builder builder = new AlertDialog.Builder(DriverShangChuanBangDanActivity.this);
        final AlertDialog alertDialog = builder.create();
        builder.setMessage("当前应用缺少-" + s + "-服务。\n\n请点击\"设置\"-\"服务\"-打开所需服务。\n\n最后点击两次后退按钮，即可返回。");
        // 拒绝, 退出应用
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                alertDialog.dismiss();
                finish();
            }
        });
        builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                alertDialog.dismiss();
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.setData(Uri.parse("package:" + BuildConfig.APPLICATION_ID));
                startActivity(intent);
            }
        });
        builder.setCancelable(false);
        builder.show();
    }


    public boolean isLocationEnabled() {
        int locationMode = 0;
        String locationProviders;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                locationMode = Settings.Secure.getInt(getContentResolver(), Settings.Secure.LOCATION_MODE);
            } catch (Settings.SettingNotFoundException e) {
                e.printStackTrace();
                return false;
            }
            return locationMode != Settings.Secure.LOCATION_MODE_OFF;
        } else {
            locationProviders = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            return !TextUtils.isEmpty(locationProviders);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        checkPermission(context);
//        boolean locationEnabled = isLocationEnabled();
//        if (locationEnabled) {
//        } else {
//            Toast.makeText(context, "请开启位置服务", Toast.LENGTH_SHORT).show();
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        destroyLocation();
    }

    private void initLocation() {
        locationClient = new AMapLocationClient(this);
        locationOption = getDefaultOption();
        //设置定位参数
        locationClient.setLocationOption(locationOption);
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
    }

    private void startLocation() {
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
    }

    private void stopLocation() {
        // 停止定位
        locationClient.stopLocation();
        lastLocation = null;
    }

    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(1000 * 60 * 15 * 1);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.Transport);
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        mOption.setGeoLanguage(AMapLocationClientOption.GeoLanguage.DEFAULT);//可选，设置逆地理信息的语言，默认值为默认语言（根据所在地区选择语言）
        return mOption;
    }

    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {

                StringBuffer sb = new StringBuffer();
                //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
                if (location.getErrorCode() == 0) {
                    lastLocation = location;
                    sb.append("定位成功" + "\n");
                    sb.append("定位类型: " + location.getLocationType() + "\n");
                    sb.append("经    度    : " + location.getLongitude() + "\n");
                    sb.append("纬    度    : " + location.getLatitude() + "\n");
                    sb.append("精    度    : " + location.getAccuracy() + "米" + "\n");
                    sb.append("提供者    : " + location.getProvider() + "\n");
//                    SPUtils.setLongitude(App.getApplication(), String.valueOf(location.getLongitude()));
//                    SPUtils.setLatitude(App.getApplication(), String.valueOf(location.getLatitude()));
//                    initDataRecyclerview(String.valueOf(location.getLongitude()), String.valueOf(location.getLatitude()));
//                    String traceDesc = location.getAddress();
//                    uploadTrack(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()), traceDesc, "2");
//                    stopNotify();
                    sb.append("速    度    : " + location.getSpeed() + "米/秒" + "\n");
                    sb.append("角    度    : " + location.getBearing() + "\n");
                    // 获取当前提供定位服务的卫星个数
                    sb.append("星    数    : " + location.getSatellites() + "\n");
                    sb.append("国    家    : " + location.getCountry() + "\n");
                    sb.append("省            : " + location.getProvince() + "\n");
                    sb.append("市            : " + location.getCity() + "\n");
                    sb.append("城市编码 : " + location.getCityCode() + "\n");
                    sb.append("区            : " + location.getDistrict() + "\n");
                    sb.append("区域 码   : " + location.getAdCode() + "\n");
                    sb.append("地    址    : " + location.getAddress() + "\n");
                    sb.append("兴趣点    : " + location.getPoiName() + "\n");

                    //定位完成的时间
                    sb.append("定位时间: " + Utils.formatUTC(location.getTime(), "yyyy-MM-dd HH:mm:ss") + "\n");
                } else {
                    //定位失败
                    sb.append("定位失败" + "\n");
                    sb.append("错误码:" + location.getErrorCode() + "\n");
                    sb.append("错误信息:" + location.getErrorInfo() + "\n");
                    sb.append("错误描述:" + location.getLocationDetail() + "\n");

                    if (location.getErrorCode() == 12) {
//                        showNotify();
                    }
                }
                sb.append("***定位质量报告***").append("\n");
                sb.append("* WIFI开关：").append(location.getLocationQualityReport().isWifiAble() ? "开启" : "关闭").append("\n");
                sb.append("* GPS状态：").append(getGPSStatusString(location.getLocationQualityReport().getGPSStatus())).append("\n");
                sb.append("* GPS星数：").append(location.getLocationQualityReport().getGPSSatellites()).append("\n");
                sb.append("* 网络类型：" + location.getLocationQualityReport().getNetworkType()).append("\n");
                sb.append("* 网络耗时：" + location.getLocationQualityReport().getNetUseTime()).append("\n");
                sb.append("****************").append("\n");
                //定位之后的回调时间
                sb.append("回调时间: " + Utils.formatUTC(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss") + "\n");

                //解析定位结果，
                String result = sb.toString();
//                tvResult.setText(result);
                LogUtils.d("定位数据是" + result);
            } else {
                LogUtils.d("定位失败，loc is null");
            }
        }
    };


    private String getGPSStatusString(int statusCode) {
        String str = "";
        switch (statusCode) {
            case AMapLocationQualityReport.GPS_STATUS_OK:
                str = "GPS状态正常";
                break;
            case AMapLocationQualityReport.GPS_STATUS_NOGPSPROVIDER:
                str = "手机中没有GPS Provider，无法进行GPS定位";
                break;
            case AMapLocationQualityReport.GPS_STATUS_OFF:
                str = "GPS关闭，建议开启GPS，提高定位质量";
                break;
            case AMapLocationQualityReport.GPS_STATUS_MODE_SAVING:
                str = "选择的定位模式中不包含GPS定位，建议选择包含GPS定位的模式，提高定位质量";
                break;
            case AMapLocationQualityReport.GPS_STATUS_NOGPSPERMISSION:
                str = "没有GPS定位权限，建议开启gps定位权限";
                break;
        }
        return str;
    }

    private void destroyLocation() {
        if (null != locationClient) {
            stopLocation();
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }


    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void receiveEvent(MessageEvent event) {
        super.receiveEvent(event);
        switch (event.getCode()) {
            case Location_Error_SIGAL:
                locationsuccess=1;
                break;
            case Location_Success_SIGAL:
                locationsuccess=0;
                break;
        }
    }
}
